package models;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;

import play.data.validation.MaxSize;
import play.data.validation.Required;
import play.db.jpa.Model;

@Entity
public class Post extends Model {
    @Required
    public String title;
    @Required
    public Date postedAt;
    @Lob
    @Required
    @MaxSize(10000)
    public String content;
    @ManyToOne
    @Required
    public User author;
    @OneToMany(targetEntity = Image.class)
    @JoinColumn(name = "post_id")
    public List<Image> images;

    public Post(User author, String title, String content) {
        this.images = new ArrayList<Image>();
        this.author = author;
        this.title = title;
        this.content = content;
        this.postedAt = new Date();
    }

    public void addImage(Image image) {
        this.images.add(image);
    }

    public Image getMainImage() {
        if (images == null || images.size() == 0) {
            return null;
        }
        for (Image image : this.images) {
            if (image.isTheMainImage) {
                return image;
            }
        }
        return images.get(0);
    }

    public Post previous() {
        return Post.find("postedAt < ? order by postedAt desc", postedAt).first();
    }

    public Post next() {
        return Post.find("postedAt > ? order by postedAt asc", postedAt).first();
    }
}
